package com.example.controller;

import com.example.pojo.common.Result;
import com.example.pojo.dto.QuestionSetImportDTO;
import com.example.pojo.entity.QuestionSet;
import com.example.service.QuestionSetService;
import com.example.service.FileParseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 习题集控制器
 */
@RestController
@RequestMapping("/api/question-sets")
public class QuestionSetController {

    @Autowired
    private QuestionSetService questionSetService;
    
    @Autowired
    private FileParseService fileParseService;

    /**
     * 获取用户的习题集列表
     * @param userId 用户ID
     * @return 习题集列表
     */
    @GetMapping("/user/{userId}")
    public Result<List<QuestionSet>> getQuestionSetsByUserId(@PathVariable Integer userId) {
        try {
            List<QuestionSet> questionSets = questionSetService.getQuestionSetsByUserId(userId);
            return Result.success("查询习题集成功", questionSets);
        } catch (Exception e) {
            return Result.error("查询习题集失败: " + e.getMessage());
        }
    }

    /**
     * 删除习题集
     * @param id 习题集ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteQuestionSet(@PathVariable Integer id) {
        try {
            questionSetService.deleteQuestionSet(id);
            return Result.success("删除习题集成功");
        } catch (Exception e) {
            return Result.error("删除习题集失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取习题集详情（包含题目列表）
     * @param id 习题集ID
     * @return 习题集详情
     */
    @GetMapping("/{id}/details")
    public Result<QuestionSet> getQuestionSetDetails(@PathVariable Integer id) {
        try {
            QuestionSet questionSet = questionSetService.getQuestionSetWithQuestions(id);
            if (questionSet != null) {
                return Result.success("查询习题集详情成功", questionSet);
            } else {
                return Result.error("习题集不存在");
            }
        } catch (Exception e) {
            return Result.error("查询习题集详情失败: " + e.getMessage());
        }
    }

    /**
     * 导入CSV习题集
     * @param importDTO 导入数据
     * @return 导入结果
     */
    @PostMapping("/import-csv")
    public Result<QuestionSet> importCsvQuestionSet(@RequestBody QuestionSetImportDTO importDTO) {
        try {
            if (importDTO.getUserId() == null) {
                return Result.error("用户ID不能为空");
            }
            
            if (importDTO.getName() == null || importDTO.getName().trim().isEmpty()) {
                return Result.error("习题集名称不能为空");
            }
            
            if (importDTO.getQuestions() == null || importDTO.getQuestions().isEmpty()) {
                return Result.error("题目列表不能为空");
            }
            
            QuestionSet questionSet = questionSetService.importCsvQuestionSet(importDTO);
            return Result.success("导入成功", questionSet);
        } catch (Exception e) {
            return Result.error("导入失败: " + e.getMessage());
        }
    }

    /**
     * 通用文件上传接口
     * @param file 上传的文件
     * @param userId 用户ID
     * @return 上传结果
     */
    @PostMapping("/upload-file")
    public Result<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file, 
                                                  @RequestParam("userId") Integer userId) {
        try {
            // 参数验证
            if (file == null || file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }
            
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }
            
            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                return Result.error("文件名不能为空");
            }
            
            String fileExtension = getFileExtension(originalFilename).toLowerCase();
            
            // 验证文件类型
            if (!isValidFileType(fileExtension)) {
                return Result.error("不支持的文件类型，仅支持CSV和Word文档(.csv, .doc, .docx)");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return Result.error("文件大小不能超过10MB");
            }
            
            // 解析文件内容
            QuestionSetImportDTO importDTO = fileParseService.parseFile(file, userId, fileExtension);
            
            // 导入到数据库
            QuestionSet questionSet = questionSetService.importCsvQuestionSet(importDTO);
            
            // 构建返回结果
            Map<String, Object> result = Map.of(
                "questionSetId", questionSet.getId(),
                "name", questionSet.getName(),
                "questionCount", questionSet.getQuestionCount(),
                "message", "文件上传并解析成功"
            );
            
            return Result.success("文件上传成功", result);
            
        } catch (Exception e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取文件扩展名
     * @param filename 文件名
     * @return 扩展名
     */
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) {
            return filename.substring(lastDotIndex + 1);
        }
        return "";
    }
    
    /**
     * 验证文件类型是否支持
     * @param extension 文件扩展名
     * @return 是否支持
     */
    private boolean isValidFileType(String extension) {
        return "csv".equals(extension) || "doc".equals(extension) || "docx".equals(extension);
    }
}
